<?php
namespace app\admin\model;
use app\admin\model\Signm;
use app\admin\model\Channel;
use think\Model;
use think\Db;

/**
 * 短信模板模型
 * @package app\admin\model
 */
class NoteM extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'bus_note';

    /**
     * 获取数据
     * @Author   lf
     * @DateTime 2018-07-03T09:42:40+0800
     * @param    [type]                   $where [查询条件（数组形式）]
     * @return   [type]                          [返回数据集]
     */
    public function getNoteAll($request)
    {
    	$user_type = session('user_type');
		$relate_id = session('relate_id');

    	$data = $this
	    	->field('bus_note.*,adm_user.username,bus_sign.sign')
	    	->join('adm_user','adm_user.id=bus_note.user_id','left')
	    	->join('bus_sign','bus_sign.id=bus_note.sign_id','left')
	    	->join('bus_channel','bus_channel.channel_id=bus_note.channel_id','left');

		switch ($user_type) {
			case 'admin':
				break;
			case 'channel':
				if(is_OneCha())
				{
					$data = $data->where(function($query){
							$query->where('bus_channel.p_id',session('relate_id'))->whereor('bus_note.channel_id',session('relate_id'));
						});
				}else{
					$data = $data->where('bus_note.channel_id',$relate_id);
				}
				break;

			default:
				/*写死通道角色权限*/
				if(session('username') == 'admin2018'){
				}else{
					return;
				}
				break;
		}

		if(!empty($request['status'])) {

            $data = $data->where('bus_sign.status', $request['status']);
        }

        if(!empty($request['ci'])) {

            $data = $data->where('bus_sign.channel_id', $request['ci']);
        }

	    $data = $data->order('status,create_time desc')
	    	->paginate($request['limit'], false,['query' => $request])
	    	->each(function($item, $key) {

	    		switch ($item->status) {
                    case '1':
                        $item->status_ = '<span class="layui-badge layui-bg-green">已通过</span>';
                        break;
                    case '2':
                        $item->status_ = '<span class="layui-badge layui-bg-orange">待审核</span>';
                        break;
                    case '3':
                        $item->status_ = '<span class="layui-badge">未通过</span>';
                        break;

	    			default:
	    				# code...
	    				break;
	    		}

			});
		return $data;
    }

    public function getMyNote()
    {
    	//是否渠道账号
    	if(session('user_type') == 'channel')
    	{
    		//是否绑定渠道
    		if( !empty(session('relate_id')) )
    		{

    		}
    	}
    }

    /**
     * 添加短信
     * @Author   lf
     * @DateTime 2018-07-02T16:14:16+0800
     * @param    [type]                   $notes     [短信内容]
     * @param    [type]                   $sign_id   [签名id]
     * @param    [type]                   $relate_id [绑定的渠道id]
     */
    public function addNoteOne($notes,$signtxt,$relate_id)
    {
        $signm = new Signm;
    	$sign_id = $signm->where('channel_id',$relate_id)->where('sign',$signtxt)->value('id');

        if(empty($sign_id))
        {
            $data = [
                "user_id"     => session('username'),
                "channel_id"  => $relate_id,
                "sign"        => $signtxt,
                "status"      => "1",
                "describe"    => "",
                "create_time" => date('Y-m-d H:i:s')
            ];
            $sign_id = $signm->insertGetId($data);
        }
    	//获取字数，第一条短信70字，之后67
		$notenum = (int)mb_strlen($notes.$signtxt, 'UTF-8');

		// $occupation = (int)($notenum/70);
        //
        $occupation = 1;

        if($notenum > 70){
    		//如果有余，+1
    		$occupation = ($notenum-70)%67==0 ? (int)($notenum/67) : (int)($notenum/67)+1;
        }

		try {
			//实例化模型添加数据
			$notem = new NoteM;
			$notem->user_id     = session('user_id');
			$notem->channel_id  = $relate_id;
			$notem->notes       = $notes;
			$notem->occupation  = $occupation;
			$notem->sign_id     = $sign_id;
			$notem->status      = '1';//跳过了申请步骤
			$notem->create_time = date('Y-m-d H:i:s');
			$notem->isUpdate(false)->save();
			trace('用户'.session('username')."申请短信模板：\r\n".json_encode($notem,JSON_UNESCAPED_UNICODE),'info');
			return "success";
		} catch (Exception $e) {
			trace('用户'.session('username')."申请短信模板失败\r\n".$e,'error');
			return "申请失败，服务器繁忙";
		}
    }
    /**
     * 编辑短信
     * @Author   lf
     * @DateTime 2018-07-02T16:14:16+0800
     * @param    [type]                   $notes     [短信内容]
     * @param    [type]                   $sign_id   [签名id]
     * @param    [type]                   $relate_id [绑定的渠道id]
     */
    public function editNoteOne($note_id,$notes,$sign_id)
    {
    	$sign = Signm::where('id',$sign_id)->value('sign');

    	//获取字数，每一条短信70字
		$notenum = (int)mb_strlen($notes.$sign, 'UTF-8');
		$occupation = (int)($notenum/70);
		//如果有余，+1
		$occupation = $notenum%70==0 ? $occupation : $occupation+1;

		try {
			//实例化模型添加数据
			$notem = NoteM::get($note_id);
			trace('用户'.session('username')."修改短信模板前：\r\n".json_encode($notem,JSON_UNESCAPED_UNICODE),'info');
			$notem->notes       = $notes;
			$notem->occupation  = $occupation;
			$notem->sign_id     = $sign_id;
			$notem->status      = '1';
			$notem->update_time = date('Y-m-d H:i:s');
			$notem->update_user = session('username');
			$notem->isUpdate(true)->save();
			trace('用户'.session('username')."修改短信模板后：\r\n".json_encode($notem,JSON_UNESCAPED_UNICODE),'info');
			return "success";
		} catch (Exception $e) {
			trace('用户'.session('username')."申请短信模板失败\r\n".$e,'error');
			return "申请失败，服务器繁忙";
		}
    }

    /**
     * 审核
     * @Author   lf
     * @DateTime 2018-07-03T09:41:19+0800
     * @param    [type]                   $status   [状态]
     * @param    [type]                   $describe [描述]
     * @param    [type]                   $notesid  [短信id]
     */
    public function setNoteApply($status,$describe,$notesid)
    {
    	try {
			//实例化模型添加数据
			$notem = NoteM::get($notesid);
			$notem->status      = $status;
			$notem->describe    = $describe;
			$notem->apply_user  = session('user_id');
			$notem->apply_time  = date('Y-m-d H:i:s');
			$notem->isUpdate(true)->save();
			trace('用户'.session('username')."审核短信模板：\r\n".json_encode($notem,JSON_UNESCAPED_UNICODE),'info');
    		echo "success";
    	} catch (Exception $e) {
			trace('用户'.session('username')."审核失败\r\n".$e,'error');
    		echo "审核失败，服务器繁忙";
    	}
    }
}